<%@ page import="org.apache.commons.fileupload.*, java.util.List, java.io.File, java.util.Iterator" %>
<%
	
	// first check if the upload request coming in is a multipart request
	boolean isMultipart = FileUpload.isMultipartContent(request);
	
	// if not, send to message page with the error message
	if(!isMultipart){
		request.setAttribute("msg", "Request was not multipart!");
		request.getRequestDispatcher("msg.jsp").forward(request, response);
		return;
	}
	
	// now lets create a handler for the upload request.
	DiskFileUpload upload = new DiskFileUpload();
	
	// parse this request by the handler
	// this gives us a list of items from the request
	List items = upload.parseRequest(request);
	
	// now iterate over this list
	Iterator itr = items.iterator();
	
	while(itr.hasNext()){
	
		FileItem item = (FileItem) itr.next();
		
		// check if the current item is a form field or an uploaded file
		if(item.isFormField()){
			
			// get the name of the field
			String fieldName = item.getFieldName();
			
			// if it is name, we can set it in request to thank the user
			if(fieldName.equals("name"))
				request.setAttribute("msg", "Thank You: " + item.getString());
				
		} else {
		
			// the item must be an uploaded file
			// save it to disk			
			File fullFile = new File(item.getName());			
			File savedFile = new File(getServletContext().getRealPath("/"), fullFile.getName());
			item.write(savedFile);
		}
	}
	
	// finally send to the msg page
	request.getRequestDispatcher("msg.jsp").forward(request, response);

	
%>